/* 引入基本模块 */
const [fs, ora, puppeteer, FakeUseragent, Message] = [
  require("fs"),
  require("ora"),
  require("puppeteer"),
  require("fake-useragent"),
  require("./tools/console.color"),
]

const axios = require("axios")
const path = require("path")
const getImgUrl = require("./tools/getImgUrl")

/* 基本配置 */
const pageOption = {
  timeout: 0,
  /* 超时时间，为0则一直等待 */
  waitUntil: "domcontentloaded" /* 满足什么条件时，页面跳转完成 */,
}
var targetWebsiteURL = "https://www.ladyphotos.com/album"
var progress = 0
var successNum = 0
var failureNum = 0
var total = 0
var processLoading = null
var timeout = 30000 /* 超时时间 */
var startTime = Date.now()
var timer = null

async function init(ID) {
  /* 创建浏览器窗口 */
  Message.info("新建浏览器中...")
  const browser = await puppeteer.launch({
    headless: true /* 默认不显示浏览器窗口 */,
  })

  /* 创建标签页 */
  Message.info("新建标签页中...")
  const [page] = await browser.pages()
  await page.setUserAgent(FakeUseragent())

  /* 进入目标页面 */
  Message.info("正在打开目标页面...")
  try {
    await page.goto(`${targetWebsiteURL}/${ID}`, pageOption)
  } catch (err) {
    Message.error(err.message)
    return
  }

  /* 目标DOM元素的selector语句 */
  const targetElementSelector = "div.big-img img"

  /* 
    page.$$eval 的第二个参数为一个回调函数（默认参数为DOM元素列表），并将返回值作为promise的结果 
    这一步根据目标的DOM元素，筛选出需要的信息
  */
  let targetList = await page.$$eval(targetElementSelector, els => els.map(t => t.src))
  try {
    await page.waitForSelector("div.big-img img")
    await page.tap("div.big-img img")
    await page.tap("div.fslightbox-slide-btn.fslightbox-flex-centered")
    await page.waitForSelector("div[data-test-class=source-main-wrapper]")
    total = await page.$$eval("div[data-test-class=source-main-wrapper]", els => els.length)
  } catch (err) {
    Message.error(err.message)
    return
  }

  /* 关闭浏览器 */
  await browser.close()

  Message.info(`共计：${total}张图片，已关闭浏览器，开始准备下载图片...`)

  /* 创建新的文件夹 */
  fs.mkdirSync(path.join("D:/Bit", ID.toString()))
  Message.success(`新建文件夹：${path.join("D:/Bit", ID.toString())} 成功`)

  timer = setInterval(() => {
    if (Date.now() - startTime > timeout) {
      processLoading.fail(`下载超时，成功数：${successNum}，失败数：${failureNum}`)
      clearInterval(timer)
    }
  }, 500)

  processLoading = ora("0%").start()
  startTime = Date.now()
  for (let i = 1; i <= total; i++) {
    downloadIMG({
      url: getImgUrl(ID, i),
      savePath: `D:/Bit/${ID}`,
      name: `${i}.jpg`,
      total,
    })
  }
}

/**
 * 根据图片链接下载图片
 * @param {string} url 图片地址
 */
function downloadIMG(option) {
  const { url, savePath, name, total } = option
  axios
    .get(url, {
      responseType: "arraybuffer",
    })
    .then(res => {
      fs.writeFile(path.join(savePath, name), res.data, "binary", err => {
        if (err) {
          throw new Error(err.message)
        }
        successNum += 1
        processLoading.text = parseInt(((successNum + failureNum) / total) * 100) + "%"
        if (progress === total) {
          processLoading.succeed(`${total}张图片已全部检索完毕！`)
          Message.success(`下载成功 ${successNum}张`)
          Message.error(`下载失败 ${failureNum}张`)
        }
      })
    })
    .catch(err => {
      failureNum += 1
      Message.error(err.message)
    })
}

init("198940")
